//
//  ProtocolViewController.swift
//  koolcar
//
//  Created by kuaimaxiansheng on 2023/10/18.
//

import UIKit
import WebKit

typealias BlockBack = () -> Void

class ProtocolViewController: BaseViewController {
    var bgView: UIView!
    var webView: WKWebView!
    var agreeBtn: UIButton!
    var titleLab: UILabel!
    var contentHtml: String = ""
    var titleStr = ""
    var isRead = false
    var tempHeight: CGFloat = 0
    var backBlock : BlockBack!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navBar.barBackgroundColor = .clear
        self.view.backgroundColor = .clear
        self.initUI()
    }
    
    func initUI(){
        let contor = UIControl(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight))
        contor.backgroundColor = .black
        contor.alpha = 0.7
        contor.addTarget(self, action: #selector(close), for: .touchUpInside)
        self.view.addSubview(contor)
        
        self.bgView = UIView(frame: CGRect(x: 30, y: (kScreenHeight - 400)/2, width: kScreenWidth - 60, height: 400))
        self.bgView.backgroundColor = .white
        self.bgView.layer.cornerRadius = 8
        self.bgView.layer.masksToBounds = true
        self.view.addSubview(self.bgView)
        
        self.titleLab = UILabel(frame: CGRect(x: 30, y: 40, width: kScreenWidth, height: 20))
        self.titleLab.textColor = .black
        self.titleLab.font = UIFont(name: Theme.PingFangSCMedium, size: 15)
        self.titleLab.textAlignment = .left
        self.titleLab.text = self.titleStr
        self.bgView.addSubview(self.titleLab)
        
        
        let configuretion = WKWebViewConfiguration.init()
        configuretion.preferences = WKPreferences()
        configuretion.preferences.minimumFontSize = 0
        configuretion.preferences.javaScriptEnabled = true
        configuretion.preferences.javaScriptCanOpenWindowsAutomatically = true
        configuretion.userContentController = WKUserContentController()
        
        webView = WKWebView.init(frame: CGRect.init(x: 30, y: self.titleLab.frame.maxY + 14, width: self.bgView.frame.size.width - 60, height: self.bgView.frame.size.height - 150), configuration: configuretion)
        webView.navigationDelegate = self
        webView.scrollView.delegate = self
        webView.uiDelegate = self
        if #available(iOS 11.0, *) {
            webView.scrollView.contentInsetAdjustmentBehavior = .never
        }
        
        webView.scrollView.showsHorizontalScrollIndicator = false
        webView.scrollView.showsVerticalScrollIndicator = false
        self.bgView.addSubview(webView)
        self.calculatorWebContent()
        
        
        self.agreeBtn = UIButton(frame: CGRect(x: 48, y: self.bgView.frame.size.height - 86, width: self.bgView.frame.size.width - 106 , height: 46))
        self.agreeBtn.titleLabel?.font = UIFont.init(name: Theme.PingFangSCMedium, size: 14)
        self.agreeBtn.setup_titleColor(color: Theme.whiteColor)
        self.agreeBtn.layer.cornerRadius = 8
        self.agreeBtn.titleEdgeInsets = UIEdgeInsets.init(top: 5, left: 5, bottom: 5, right: 5)
        self.agreeBtn.layer.masksToBounds = true
        self.agreeBtn.addTarget(self, action: #selector(agreeBtnAntion), for: .touchUpInside)
        self.agreeBtn.setup_titleLabel(text: MMLocalizedString("read_agree_agreement", comment: "我已阅读并同意协议"))
        self.agreeBtn.titleLabel?.numberOfLines = 0
        self.agreeBtn.titleLabel?.lineBreakMode = .byWordWrapping
        self.bgView.addSubview(self.agreeBtn)
        self.agreeBtn.backgroundColor = Theme.mainColor
        
        
        let hideBtn = UIButton(frame: CGRect(x: (kScreenWidth - 30)/2, y: self.bgView.frame.maxY + 20, width: 30, height: 30))
        hideBtn.setImage(UIImage(named: "icon_hide"), for: .normal)
        hideBtn.addTarget(self, action: #selector(close), for: .touchUpInside)
        self.view.addSubview(hideBtn)
        
    }
    
    
    //计算webView
    func calculatorWebContent() {
        if self.webView == nil {
            let configuretion = WKWebViewConfiguration.init()
            configuretion.preferences = WKPreferences()
            configuretion.preferences.minimumFontSize = 0
            configuretion.preferences.javaScriptEnabled = true
            configuretion.preferences.javaScriptCanOpenWindowsAutomatically = true
            configuretion.userContentController = WKUserContentController()
            webView = WKWebView.init(frame: CGRect.init(x: 0, y: 0, width: kScreenWidth, height: 0), configuration: configuretion)
            webView.navigationDelegate = self
            webView.uiDelegate = self
            if #available(iOS 11.0, *) {
                webView.scrollView.contentInsetAdjustmentBehavior = .never
            }
            webView.scrollView.isScrollEnabled = false
            webView.scrollView.showsHorizontalScrollIndicator = false
        }
        
        if !(self.contentHtml).contains("<html") {
            let formatWeb = """
                    <!DOCTYPEhtml>
                        <html>
                        <head>
                            <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"name="viewport">
                            <meta http-equiv="Content-Type"content="text/html; charset=UTF-8">
                        </head>
                        <style type="text/css">
                           
                        </style>
                        <body>
                                 %@
                    <div
                    
                         <p style="color:white; font-size:30px;">button</p>
                          </div>
                        </body>
                        </html>
                    """
            let tempStr = String(format: formatWeb,self.contentHtml)
            self.webView.loadHTMLString(tempStr, baseURL: nil)
        }else{
            self.webView.loadHTMLString(contentHtml, baseURL: nil)
        }
    }
    
    
    //MARK: - Antion
    
    //已阅读并同意协议
    @objc func agreeBtnAntion() {
        self.isRead = true
        if self.backBlock != nil{
            self.backBlock()
            self.navigationController?.popViewController(animated: false)
        }
        self.close()
    }
    
    
    @objc func close(){
        UIView.animate(withDuration: 0.2) {
            self.bgView.alpha = 0
        } completion: { flag in
            self.dismiss(animated: false)
        }
    }
    
    
}

extension ProtocolViewController: WKNavigationDelegate,UIScrollViewDelegate {
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        webView.evaluateJavaScript("document.body.scrollHeight") { [weak self] (result, error) in
            //            if let tempHeight: CGFloat = result as? CGFloat {
            //                self?.tempHeight = tempHeight
            //                print(tempHeight)
            //                if (self?.webView.frame.size.height ?? 0) > (tempHeight  + TabbarHeight) {
            //                    self?.agreeBtn.backgroundColor = Theme.mainColor
            //                }
            //            }
        }
    }
    
    
}


